<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>{{if .HasData}}编辑接口{{else}}创建接口{{end}} - ApiServ</title>
    {{template "head.html" .}}
    {{if $.IsDev}}
        <link rel="stylesheet" href="/static/css/jsoneditor.min.css">
    {{else}}
            {{/*如果您有自己的静态资源链接，请换成自己的，这里后期我会做referer限制*/}}
        <link rel="stylesheet" href="http://static.apiserv.me/jsoneditor.min.css">
    {{end}}
    <style>
        div.jsoneditor{border:2px solid #bdc3c7 !important;border-radius: 6px;}
    </style>
</head>
<body id="as-api-edit">
    <div class="container-fluid">
        <div class="container">
            <div class="row">
                <div class="col-xs-12 as-mgt-50px">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            {{if .HasData}}
                                <strong>编辑接口</strong>
                            {{else}}
                                <strong>创建接口</strong>
                            {{end}}
                                (<a href="javascript:void(0);"  data-toggle="modal" data-target="#ModalHelp"> <i class="fa fa-question"></i> 帮助指南</a>)
                            <span class="pull-right">
                                <a href="{{urlfor "UserController.Apis"}}" title="接口管理"> <i class="fa fa-mail-reply"></i> 返回列表</a>
                            </span>
                        </div>
                        <div class="panel-body">
                            <form role="form" data-url="{{urlfor "UserController.Apis"}}" method="post" class="json-form">
                                <div class="form-group">
                                    <label>接口名称 <span class="text-danger">*</span> </label>
                                    <input type="text" required="required" class="form-control" value="{{.Api.Title}}" name="Title" placeholder="请输入接口名称，如‘用户登录’">
                                </div>
                                <input type="hidden" name="Id" value="{{.Api.Id}}">
                                <div class="form-group">
                                    <label>API <span class="text-danger">*</span></label>
                                    <input type="text" required="required" class="form-control" name="Api" value="{{.Api.Api}}" placeholder="请输入API，如‘/user/login’">
                                </div>
                                <div class="form-group">
                                    <label>请求方法 <span class="text-danger">*</span></label>
                                    <div class="checkbox">
                                        <label><input type="checkbox" name="Methods" value="GET" {{if and (eq $.HasData true) (InMethods "GET" (Split .Api.Methods ","))}}checked{{end}}> GET</label>
                                        <label><input type="checkbox" name="Methods" value="POST" {{if and (eq $.HasData true) (InMethods "POST" (Split .Api.Methods ","))}}checked{{end}}> POST</label>
                                        <label><input type="checkbox" name="Methods" value="HEAD" {{if and (eq $.HasData true) (InMethods "HEAD" (Split .Api.Methods ","))}}checked{{end}}> HEAD</label>
                                        <label><input type="checkbox" name="Methods" value="PUT" {{if and (eq $.HasData true) (InMethods "PUT" (Split .Api.Methods ","))}}checked{{end}}> PUT</label>
                                        <label><input type="checkbox" name="Methods" value="OPTIONS" {{if and (eq $.HasData true) (InMethods "OPTIONS" (Split .Api.Methods ","))}}checked{{end}}> OPTIONS</label>
                                        <label><input type="checkbox" name="Methods" value="DELETE" {{if and (eq $.HasData true) (InMethods "DELETE" (Split .Api.Methods ","))}}checked{{end}}> DELETE</label>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label>请求参数 (<a href="javascript:void(0);" class="params-add"><i class="fa fa-plus"></i>加一行</a>)</label>
                                    <div class="table-responsive">
                                        <table class="table table-params">
                                            <thead>
                                            <tr>
                                                <th class="nopadding-left">参数名</th>
                                                <th>参数类型</th>
                                                <th>参数说明</th>
                                                <th>操作</th>
                                            </tr>
                                            </thead>
                                            <tbody>

                                            {{if eq $.HasData true}}
                                                {{range (HandleParams .Api.Params)}}
                                                    <tr>
                                                        <td class="nopadding-left">
                                                            <input type="text" class="form-control" placeholder="如‘username’" value="{{.ParamsName}}" name="ParamsName">
                                                        </td>
                                                        <td>
                                                            <select name="ParamsType" class="form-control">
                                                                <option value="string" {{if eq .ParamsType "string"}}selected{{end}}>string</option>
                                                                <option value="file" {{if eq .ParamsType "file"}}selected{{end}}>file</option>
                                                                <option value="array" {{if eq .ParamsType "array"}}selected{{end}}>array</option>
                                                                <option value="int" {{if eq .ParamsType "int"}}selected{{end}}>int</option>
                                                                <option value="int32" {{if eq .ParamsType "int32"}}selected{{end}}>int32</option>
                                                                <option value="int64" {{if eq .ParamsType "int64"}}selected{{end}}>int64</option>
                                                                <option value="float" {{if eq .ParamsType "float"}}selected{{end}}>float</option>
                                                                <option value="float32" {{if eq .ParamsType "float32"}}selected{{end}}>float32</option>
                                                                <option value="float64" {{if eq .ParamsType "float64"}}selected{{end}}>float64</option>
                                                            </select>
                                                        </td>
                                                        <td>
                                                            <input type="text" class="form-control" value="{{.ParamsState}}" placeholder="如‘用户名，字符串，2-20个字符’" name="ParamsState">
                                                        </td>
                                                        <td>
                                                            <a href="javascript:void(0);" class="btn btn-danger params-del btn-block"> <i class="fa fa-remove"></i> 删除</a>
                                                        </td>
                                                    </tr>
                                                {{end}}
                                            {{end}}

                                            <tr>
                                                <td class="nopadding-left">
                                                    <input type="text" class="form-control" placeholder="如‘username’" name="ParamsName">
                                                </td>
                                                <td>
                                                    <select name="ParamsType" class="form-control">
                                                        <option value="string">string</option>
                                                        <option value="file">file</option>
                                                        <option value="array">array</option>
                                                        <option value="int">int</option>
                                                        <option value="int32">int32</option>
                                                        <option value="int64">int64</option>
                                                        <option value="float">float</option>
                                                        <option value="float32">float32</option>
                                                        <option value="float64">float64</option>
                                                    </select>
                                                </td>
                                                <td>
                                                    <input type="text" class="form-control" placeholder="如‘用户名，字符串，2-20个字符’" name="ParamsState">
                                                </td>
                                                <td>
                                                    <a href="javascript:void(0);" class="btn btn-danger params-del btn-block"> <i class="fa fa-remove"></i> 删除</a>
                                                </td>
                                            </tr>

                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                                <div class="form-group clearfix">
                                    <label class="col-xs-12 nopadding-left">成功时的JSON响应</label>
                                    <div class="col-xs-12 nopadding">
                                        <div class="editor-json" id="JsonSucc"></div>
                                        <textarea name="JsonSucc" class="hidden as-json" rows="8">{{.Api.JsonSucc}}</textarea>
                                    </div>
                                </div>
                                <div class="form-group clearfix">
                                    <label class="col-xs-12 nopadding-left">失败时的JSON响应</label>
                                    <div class="col-xs-12 nopadding">
                                        <div class="editor-json" id="JsonErr"></div>
                                        <textarea name="JsonErr" class="hidden as-json" rows="8">{{.Api.JsonErr}}</textarea>
                                    </div>
                                </div>


                                <div class="form-group">
                                    <label>响应说明 (<a href="javascript:void(0);" class="response-auto" title="从上面的json响应中自动提取字段"><i class="fa fa-refresh"></i>自提字段</a> | <a href="javascript:void(0);" class="response-add"><i class="fa fa-plus"></i>加一行</a>)</label>
                                    <div class="table-responsive">
                                        <table class="table table-response">
                                            <thead>
                                            <tr>
                                                <th class="nopadding-left">响应字段</th>
                                                <th>字段说明</th>
                                                <th>操作</th>
                                            </tr>
                                            </thead>
                                            <tbody>
                                            {{if eq $.HasData true}}
                                                {{range (HandleResp .Api.Resp)}}
                                                <tr>
                                                    <td class="nopadding-left">
                                                        <input type="text" class="form-control" value="{{.ResponseField}}" placeholder="如‘nickname’" name="ResponseField">
                                                    </td>
                                                    <td>
                                                        <input type="text" class="form-control" value="{{.ResponseState}}" placeholder="如‘用户昵称’" name="ResponseState">
                                                    </td>
                                                    <td>
                                                        <a href="javascript:void(0);" class="btn btn-danger params-del btn-block"> <i class="fa fa-remove"></i> 删除</a>
                                                    </td>
                                                </tr>
                                                {{end}}
                                            {{end}}
                                            <tr>
                                                <td class="nopadding-left">
                                                    <input type="text" class="form-control" placeholder="如‘nickname’" name="ResponseField">
                                                </td>
                                                <td>
                                                    <input type="text" class="form-control" placeholder="如‘用户昵称’" name="ResponseState">
                                                </td>
                                                <td>
                                                    <a href="javascript:void(0);" class="btn btn-danger params-del btn-block"> <i class="fa fa-remove"></i> 删除</a>
                                                </td>
                                            </tr>

                                            </tbody>
                                        </table>
                                    </div>

                                </div>


                                <button type="submit" class="btn btn-primary btn-block">提交</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
  </div>
    <div class="modal fade" id="ModalHelp" tabindex="-1" role="dialog" aria-labelledby="ModalHelpLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="ModalHelpLabel">帮助指南</h4>
                </div>
                <div class="modal-body">
                    <strong>参数相关</strong>
                    <div class="text-indent">接口在调用的时候，默认返回成功时的json数据，如需返回错误时的json数据，则请在请求参数中添加‘as-succ’参数，并将参数值设置为false。其实，‘as-’是ApiServ的前缀，用于与您的其他参数区分开。</div>
                    <strong>图片相关</strong>
                    <div class="text-indent">在接口返回的json数据中，难免需要用到各种尺寸大小的图片，为此，ApiServ借助阿里云的OSS，开启了一个图片处理服务，内置了20张图片(分别是1.png,2.png,...,20.png)，大家可以根据自己的需要，按照规则配置图片的尺寸大小。</div>
                    <div class="text-indent">
                        域名：http(s)://apiserv.oss-cn-hangzhou.aliyuncs.com
                    </div>
                    <div class="text-indent">示例：
                        <ul>
                            <li>返回宽高为100x100像素的图片(比如作为用户头像)</li>
                            <li>http(s)://apiserv.oss-cn-hangzhou.aliyuncs.com/1.png?x-oss-process=image/resize,m_fill,<strong class="text-danger">w_100</strong>,<strong class="text-danger">h_100</strong>,limit_0/auto-orient,0</li>
                            <li>其中，w_100,h_100分表表示宽100px，高100px，同理，如果您要配置300x300的图片，则使用w_300,h_300即可。由于内置了20张图片，所以您可以使用1.png或者2.png或者20.png等图片</li>
                        </ul>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal">知道了</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>
    {{template "foot.html" .}}
    {{if $.IsDev}}
        <script src="/static/js/ace.js"></script>
        <script src="/static/js/jsoneditor-minimalist.min.js"></script>
    {{else}}
        {{/*如果您有自己的静态资源链接，请换成自己的，这里后期我会做referer限制*/}}
        <script src="http://static.apiserv.me/ace.js"></script>
        <script src="http://static.apiserv.me/jsoneditor-minimalist.min.js"></script>
    {{end}}
    <script>
        $(function(){
         // create the editor
            var containers =$(".editor-json");
            var options = {
                mode: 'code',
                ace: ace
            };
            var jsonSucc={},jsonErr={};
            var ContainerSucc=document.getElementById("JsonSucc"),ContainerErr=document.getElementById("JsonErr");
            try {
                jsonSucc=JSON.parse($("#JsonSucc").siblings("textarea").val());
            }catch (e){
                console.log(e.toString());
            }
            try {
                jsonErr=JSON.parse($("#JsonErr").siblings("textarea").val());
            }catch (e){
                console.log(e.toString());
            }
            var editorSucc = new JSONEditor(ContainerSucc, options, jsonSucc);
            var editorErr = new JSONEditor(ContainerErr, options, jsonErr);


            //自动提取字段并追加[这个必须放在这里，毕竟editor在这里]
            $(".response-auto").click(function () {
                var respSucc=new Set(),respErr=new Set(),keys=[];
                try{
                    respSucc=EnumKeys(editorSucc.get())
                }catch(e) {
                    console.log(e.toString());
                }
                try{
                    respErr=EnumKeys(editorErr.get())
                }catch(e) {
                    console.log(e.toString());
                }
                keys.push(...respSucc,...respErr);
                var ksets=new Set(keys);
                var html =[];
                for(var key of ksets){
                    html.push('<tr>\n' +
                            '                                                <td class="nopadding-left">\n' +
                            '                                                    <input type="text" class="form-control" value="'+key+'" placeholder="如‘nickname’" name="ResponseField">\n' +
                            '                                                </td>\n' +
                            '                                                <td>\n' +
                            '                                                    <input type="text" class="form-control" placeholder="如‘用户昵称’" name="ResponseState">\n' +
                            '                                                </td>\n' +
                            '                                                <td>\n' +
                            '                                                    <a href="javascript:void(0);" class="btn btn-danger params-del btn-block"> <i class="fa fa-remove"></i> 删除</a>\n' +
                            '                                                </td>\n' +
                            '                                            </tr>')
                }
                $("#as-api-edit .table-response tbody").prepend(html.join(""));

            });

            $(".json-form [type=submit]").click(function(e){
                e.preventDefault();
                var form=$(this).parent("form"),ms=new Date().getMilliseconds(),cls="danger-"+ms,passNum=0;
                try {
                    form.find("[name=JsonSucc]").val(JSON.stringify(editorSucc.get()));
                    passNum++;
                } catch (error) {
                    $("#JsonSucc").after('<div class="text-danger '+cls+'">'+error.toString()+'</div>');
                    editorSucc.focus();
                }
                try {
                    form.find("[name=JsonErr]").val(JSON.stringify(editorErr.get()));
                    passNum++;
                } catch (error) {
                    $("#JsonErr").after('<div class="text-danger '+cls+'">'+error.toString()+'</div>');
                    editorErr.focus();
                }
                setTimeout(function(){
                    $("."+cls).remove();
                }, 3000);
                if(passNum==2){
                    $.post(form.attr("action"),form.serialize(),function (ret) {
                        if (ret.Status==1){
                            location.href=form.attr("data-url");
                        }else{
                            bootoast({
                                message: ret.Msg,
                                type: 'danger',
                                position:'right-bottom',
                                timeout:3
                            });
                        }
                    })
                }
            });

            //提取json中的key
            function EnumKeys(js) {
                var keys =[];
                $.each(js,function (key,val) {
                    if (typeof key=='string'){
                        keys.push(key);
                    }
                    if(typeof val=='object' && val!=null && val!=undefined){
                        keys.push(...EnumKeys(val));
                    }
                });
                return new Set(keys);
            }

        });
  
    </script>
</body>
</html>
